package com.tianhua.javs.core.func.translate.condition;

import com.tianhua.javs.client.bean.JavsSegmentBean;
import com.tianhua.javs.client.func.ITranslatorFunc;
import com.tianhua.javs.core.annotations.Segment;
import com.tianhua.javs.core.constant.TagConstants;
import com.tianhua.javs.core.parse.JavsContentParseService;
import com.tianhua.javs.core.parse.SegmentSpreadParseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Description:
 * date: 2022/2/12
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component(value = "ifretf")
@Segment(tag = "ifretf",scriptFuncBean = "conditionFunc", packageArr = {"com.coderman.util.result.ResultDto"})
@Slf4j
public class Ifretf implements ITranslatorFunc {
    @Autowired
    private JavsContentParseService javsContentParseService;
    @Autowired
    private SegmentSpreadParseService segmentSpreadParseService;

    @Override
    public JavsSegmentBean translate(String shellSegment) {
        String tempSegment = shellSegment.trim();
        List<String> paramList = javsContentParseService.getParamList(tempSegment);
        if(paramList.size() < 2){
            log.warn("javs func param count not match. shellSegment = {}",shellSegment);
        }
        if(tempSegment.startsWith("ifretf(")){
            String blank = segmentSpreadParseService.getBlankPrefix(shellSegment);

            if(paramList.size() == 2){
                StringBuilder builder = new StringBuilder(blank + "if");
                builder.append(TagConstants.BRACKET_LEFT);
                builder.append(paramList.get(0));
                builder.append(TagConstants.BRACKET_RIGHT);
                builder.append("{\n");
                builder.append(blank + "    return ResultDto.fail("+paramList.get(1)+");\n");
                builder.append(blank + "}\n");
                return JavsSegmentBean.getMatchInstance(builder.toString());
            }
            else if(paramList.size() == 3){
                StringBuilder builder = new StringBuilder(blank + "if");
                builder.append(TagConstants.BRACKET_LEFT);
                builder.append(paramList.get(0));
                builder.append(TagConstants.BRACKET_RIGHT);
                builder.append("{\n");
                builder.append(blank + "    return ResultDto.fail("+paramList.get(1) +", "+ paramList.get(2)+")\n");
                builder.append(blank + "}\n");
                return JavsSegmentBean.getMatchInstance(builder.toString());
            }
        }
        return JavsSegmentBean.getInstance(shellSegment);
    }
}
